package com.junyuan.bletooth;

import android.app.Application;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.junkchen.blelib.BleService;
import com.junyuan.bletooth.utils.BytesUtil;

import java.util.List;

/**
 * Created by Administrator on 2016/9/7.
 */
public class MyApplication extends Application {

    public static MyApplication instance;
    public BleService mBleService;
    public BluetoothGattCharacteristic mCharacteristic;
    String backData;
    Handler handler = new Handler();

    private boolean mIsBind;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBleService = ((BleService.LocalBinder) service).getService();
            mIsBind = true;
            if (mBleService.initialize()) {
                if (mBleService.enableBluetooth(true)) {
                    Toast.makeText(getApplicationContext(), "Bluetooth was opened", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), "not support Bluetooth", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBleService = null;
            mIsBind = false;
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_CONNECTED);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction("linkble");
        filter.addAction(BleService.ACTION_BLUETOOTH_DEVICE);
        filter.addAction(BleService.ACTION_SCAN_FINISHED);
        registerReceiver(bleReceiver, filter);

        doBindService();
    }


    private void linkBle() {
        if (mBleService != null) {
            mBleService.initialize();
            mBleService.enableBluetooth(true);
            mBleService.scanLeDevice(true, 200);
            Log.d("mytag", "开始扫描蓝牙设备");
        }
    }


    public BroadcastReceiver bleReceiver = new BroadcastReceiver() {


        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BleService.ACTION_GATT_CONNECTED)) {
                Toast.makeText(getApplicationContext(), "蓝牙以连接", Toast.LENGTH_SHORT).show();
                sendAndReceiveData();
                Log.d("mytag", "蓝牙链接");
                mBleService.scanLeDevice(false);
            } else if (intent.getAction().equals(BleService.ACTION_GATT_DISCONNECTED)) {
                Toast.makeText(getApplicationContext(), "蓝牙以断开", Toast.LENGTH_SHORT).show();
                Log.d("mytag", "蓝牙断开");
                mBleService.scanLeDevice(true, 200);


            } else if (intent.getAction().equals("linkble")) {
                linkBle();
            } else if (intent.getAction().equals(BleService.ACTION_BLUETOOTH_DEVICE)) {
                String name = intent.getStringExtra("name");
                String address = intent.getStringExtra("address");
                if (name != null) {
                    if (name.equals("AACC")) {
                        mBleService.connect(address);
                        mBleService.scanLeDevice(false);
                    }
                }
            } else if (intent.getAction().equals(BleService.ACTION_SCAN_FINISHED)) {
                if (!mBleService.isConnect()) {
                    mBleService.scanLeDevice(true);
                }
            }
        }
    };

    /**
     * 发送蓝牙指令
     *
     * @param data 要发送的数据
     * @param time 延迟发送的时间ms
     */
    public void sendData(final String data, long time) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mBleService != null && mCharacteristic != null) {
                    mBleService.writeCharacteristic(mCharacteristic, data);
                }
            }
        }, time);
    }

    public void sendAndReceiveData() {
        mBleService.setOnServicesDiscoveredListener(new BleService.OnServicesDiscoveredListener() {
            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                Log.d("mytag", "onServicesDiscovered Status:" + status);

                List<BluetoothGattService> Services = gatt.getServices();
                for (BluetoothGattService service : Services) {
                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                    for (BluetoothGattCharacteristic characteristic : characteristics) {
                        if (characteristic.getUuid().toString().equals("0000ffe1-0000-1000-8000-00805f9b34fb")) {
                            mBleService.setCharacteristicNotification(characteristic, true);
                            mCharacteristic = characteristic;
                            boolean isSend = mBleService.writeCharacteristic(characteristic, "hello");
                            Log.d("mytag", "是否发送成功" + isSend);
                        }
                    }
                }
            }
        });


        mBleService.setOnDataAvailableListener(new BleService.OnDataAvailableListener() {

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, int status) {
                //处理特性读取返回的数据(暂时不用)
                Log.d("mytag", "onCharacteristicRead Status:" + status);
                List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                for (BluetoothGattDescriptor descriptor : descriptors) {
                    String data = BytesUtil.bytesToHexString(descriptor.getValue());
                    Log.d("mytag", "onCharatersiticRead Data:" + data);
                }
            }


            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                //处理通知返回的数据(当收到数据改变通知时调用)
                Log.d("mytag", "onCharacteristicChanged");
                Log.d("mytag", "收到蓝牙发来数据：" + new String(characteristic.getValue()));
                backData = new String(characteristic.getValue());

                Intent intent = new Intent();
                intent.setAction("BackData");
                intent.putExtra("BackData", backData);
                sendBroadcast(intent);
            }

            @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                Log.d("mytag", "onDescriptorRead");
            }
        });

    }

    private void doBindService() {
        Intent serviceIntent = new Intent(this, BleService.class);
        this.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void doUnBindService() {
        if (mIsBind) {
            this.unbindService(serviceConnection);
            mBleService = null;
            mIsBind = false;
        }
    }


    @Override
    public void onTerminate() {
        super.onTerminate();
        if (mBleService != null) {
            if (mBleService.isConnect()) {
                mBleService.disconnect();
            }
            mBleService.close();
            doUnBindService();
        }
        unregisterReceiver(bleReceiver);
    }
}
